package com.ucw.mountain.datasource.factory;

import javax.annotation.PreDestroy;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.ucw.mountain.pageinterceptor.PageInterceptor;

@Component
@Configuration
public class SlaveDB {

	// private static Logger logger = LoggerFactory.getLogger(MasterDB.class);
	@Autowired
	private DatasourceProperties datasourceProperties;

	public SlaveDB() {
	}

	public SqlSessionTemplate getSqlSession() {
		try {
			return new SqlSessionTemplate(slaveSqlSessionFactoryBean().getObject());
		} catch (Exception e) {
			// logger.error(e.getMessage(), e);
		}
		return null;
	}

	@Bean
	@Scope("prototype")
	SqlSessionTemplate slaveSqlSessionTemplate() {
		return this.getSqlSession();
	}

	/*
	 * 设置分页拦截器的Plugin
	 * 
	 * @Author Kasp at 549172054@qq.com
	 * 
	 * @Create at 2017-5-23 13:42:59
	 * 
	 */
	@Bean
	SqlSessionFactoryBean slaveSqlSessionFactoryBean() {
		SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
		sqlSessionFactory.setDataSource(slaveDataSource());
		PageInterceptor pageInterceptor = new PageInterceptor();
		sqlSessionFactory.setPlugins(new Interceptor[] { pageInterceptor });
		return sqlSessionFactory;
	}

	@Bean
	DataSource slaveDataSource() {
		PoolProperties p = DBHelper.buildPoolProperties(datasourceProperties.getSlave());
		p.setDefaultReadOnly(true);
		p.setLogAbandoned(true);
		return new DataSource(p) {
			@PreDestroy
			public void close() {
				super.close(true);
			}
		};
	}

}
